<?php
namespace app\common\traits;

use think\facade\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\facade\View;


trait Backend
{
    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else {
            if (key_exists($this->excludeFields, $params)) {
                unset($params[$this->excludeFields]);
            }
        }
        return $params;
    }
    /**
     * 渲染变量
     */
    public function assign($name,$value){
        View::assign($name,$value);
    }
    /**
     * 渲染模板
     */
    public function fetch(string $template='',array $array = []){
        View::fetch($template,$array);
    }
    /**
     * 查看
     */
    public function index()
    {
        try {
            $where = [];
            $with = '';
            if (method_exists($this, 'get_where')) {
                $where = $this->get_where($this->request->param() ?? []);
            }

            if (method_exists($this, 'get_with')) {
                $with = $this->get_with();
            }
            $this->request->filter(['strip_tags']);

            $list = $this->model->with($with)->where($where)->field($this->field ?? '*')->order($this->order ?? 'id desc')->paginate($this->request->param('per_page'), false, ['query' => $this->request->param()]);

            $result = array('code'=>200,"data" => ['rows' => $list]);
            if (method_exists($this, 'get_class') && !empty(is_array($this->get_class())) && $this->get_class) {
                $result = ['code' => 200, "data" => ['rows' => $list, 'class' => $this->get_class()]];
            }
        } catch (\Exception $e) {
            $result = ['code' => 400, 'msg' => $e->getMessage()];
        }
        return json($result);
    }

    /**
     * 添加  POST
     */
    public function post_add()
    {
        $params = $this->request->param();
        if ($params) {
            $params = $this->preExcludeFields($params);
            $result = false;

            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\terminalModel\\", "\\terminalValidate\\", get_class($this->model));
                    if (get_class($this->model) == 'app\common\storemodel\SystemAdmin') {
                        $name = str_replace("\\storemodel\\", "\\storeValidate\\", get_class($this->model));
                    }

                    is_bool($this->modelValidate) ? validate($name)->scene('add')->check($params) : validate($name);
                }
                $result = $this->model->save($params);

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                return json(['code' => 400, 'msg' => $e->getError()]);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 400, 'msg' => $e->getMessage()]);
            }
            if ($result !== false) {
                //recover_log(1,$this->menu_data['name']);
                return json(['code' => 200, 'msg' => '添加成功']);
            } else {
                return json(['code' => 400, 'msg' => '添加失败']);
            }
        }
        return json(['code' => 400, 'msg' => '未填写任何参数']);
    }

    /**
     * 添加  GET
     */
    public function get_add()
    {
        try {
            $result = ['code' => 200, "data" => []];
            if (method_exists($this, 'get_class')) {
                $result = ['code' => 200, "data" => ['class' => $this->get_class()]];
            }
        } catch (\Exception $e) {
            $result = ['code' => 400, 'msg' => $e->getMessage()];
        }
        return json($result);
    }


    /**
     * 编辑 POST
     */
    public function post_edit()
    {
        $ids = $this->request->param('id');
        $row = $this->model->field($this->edit_field ?? '*')->find($ids);
        if (empty($row)) return json(['code' => 400, 'msg' => '未找到数据']);
        $params = $this->request->param();
        if ($params) {
            $params = $this->preExcludeFields($params);
            $result = false;

            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\terminalModel\\", "\\terminalValidate\\", get_class($this->model));
                    if (get_class($this->model) == 'app\common\storemodel\SystemAdmin') {
                        $name = str_replace("\\storemodel\\", "\\storeValidate\\", get_class($this->model));
                    }

                    is_bool($this->modelValidate) ? validate($name)->scene('edit')->check($params) : validate($name)->check($params);

                }
                $result = $row->save($params);

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                return json(['code' => 400, 'msg' => $e->getError()]);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 400, 'msg' => $e->getMessage()]);
            }
            if ($result !== false) {
                return json(['code' => 200, 'msg' => '修改成功']);
            } else {
                return json(['code' => 400, 'msg' => '修改失败']);
            }
        }
        return json(['code' => 400, 'msg' => '未做任何修改']);
    }

    /**
     * 编辑 GET
     */
    public function get_edit()
    {
        $ids = $this->request->param('id','');
        $row = $this->model->field($this->edit_field ?? '*')->find($ids);
//        dd($this->edit_field);
        if (empty($row)) json(['code' => 200, 'msg' => '未找到数据']);
        try {
            $result = array('code'=>200,"data" => ['row' => $row]);
            if (method_exists($this, 'get_class')) {
                $result = ['code' => 200, "data" => ['row' => $row, 'class' => $this->get_class()]];
            }
        } catch (\Exception $e) {
            $result = ['code' => 400, 'msg' => $e->getMessage()];
        }
        return json($result);
    }


    /**
     * 删除
     */
    public function del()
    {
        $ids = $this->request->param('id/a');
        if (!$ids) return json(['code' => 400, 'msg' => '未传入主键']);
        $pk = $this->model->getPk();
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }
        if ($count) {
            //recover_log(3,$this->menu_data['name']);
            $result = ['code' => 200, 'msg' => '删除成功'];
        } else {
            $result = ['code' => 200, 'msg' => '未删除任何数据'];
        }
        return json($result);

    }
}